/**
 *
 * 2007-11-2 下午05:42:07
 * @author xuhuan
 */

package edu.ccut.saturn.studio.wfg.xml.loader;

import java.util.List;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import edu.ccut.saturn.studio.wfg.model.Connection;
import edu.ccut.saturn.studio.wfg.model.Shape;
import edu.ccut.saturn.studio.wfg.wfgmodel.SaturnName;
import edu.ccut.saturn.studio.wfg.wfgmodel.SaturnRouter;
import edu.ccut.saturn.studio.wfg.wfgmodel.SaturnRouterNode;

public class ConnectionLoader extends NodeLoader {

	public void loadNodeForConnection(Element root, List<Shape> shapes) {
		NodeList connectionNodes = root.getElementsByTagName(SaturnName.CONNECTION_CONNECTION);

		for (int i = 0; i < connectionNodes.getLength(); ++i) {
			Node connectionNode = connectionNodes.item(i);
			String sourceId = super.getNodeAttributeValue(connectionNode,
					SaturnName.CONNECTION_SOURCE);
			String targetId = super.getNodeAttributeValue(connectionNode,
					SaturnName.CONNECTION_TARGET);
			Shape source = this.getShapeByKey(shapes, sourceId);
			Shape target = this.getShapeByKey(shapes, targetId);

			if (source != null && target != null) {
				Connection connection = new Connection(source, target, Connection.SOLID_CONNECTION, "");
				if (source instanceof SaturnRouterNode) {
					List<SaturnRouter> saturnRouters = ((SaturnRouterNode) source).getRouterList();
					for (int j = 0; j < saturnRouters.size(); j++) {
						SaturnRouter router = saturnRouters.get(j);
						if (router.getId().equals(target.getId())) {
							connection.setLineName(router.getLineName());
						}
					}
				}
			} else {
				// TODO:这时怎么办？
			}
		}
	}

	private Shape getShapeByKey(List<Shape> shapes, String key) {
		for (Shape shape : shapes) {
			if (shape.getId().equals(key))
				return shape;
		}

		return null;
	}

	public List<Shape> loadNodes(Element root) {
		return null;
	}
}
